import { requestClient } from '#/api/request';
/**
 * 文件对象转base64字符串
 * @author lizhao
 * @param {object} file input选择后的文件对象
 * @return {object} str 返回Promise
 * **/
function base64(file : any) : object {
	return new Promise((resolve, reject) => {
		const reader : any = new FileReader()
		let fileResult = {
			base64: '',
			base64slice: ''
		}
		reader.readAsDataURL(file)
		reader.onload = function () {
			// 去除头部data:image/jpg;base64,留下base64编码后的字符串
			const index = reader.result.indexOf(',')
			const str = reader.result.slice(index + 1, reader.result.length)
			fileResult = {
				base64: reader.result,
				base64slice: str
			}
		}
		reader.onerror = function (error : any) {
			reject(error)
		}
		reader.onloadend = function () {
			resolve(fileResult)
		}
	})
}

/**
 * 网络地址转转base64字符串
 * @author lizhao
 * @param {object} url 网络地址如http://example.com/image.png
 * @return {object} str 返回Promise
 * **/
async function urlToBase64(url) {
	let baseURL = process.env.NODE_ENV === 'development' ? '/api/file/web/file/record/' : window.location.origin + '/api/file/web/file/record/'
	try {
		const response = await requestClient.get(baseURL + url, { responseType: 'blob' });
		const blob = response.data;
		const reader = new FileReader();
		await new Promise((resolve, reject) => {
			reader.onloadend = () => resolve(reader.result);
			reader.onerror = reject;
			reader.readAsDataURL(blob);
		});
		return reader.result
	} catch (error) {
		console.error('There has been a problem with your axios operation:', error);
	}

	// return request({
	// 	url: url,
	// 	method: 'post',
	// 	data: param
	// })
	// 	.then(response => {
	// 		if (!response.ok) {
	// 			throw new Error('网络响应不正常');
	// 		}
	// 		return response.blob();
	// 	})
	// 	.then(blob => {
	// 		return new Promise((resolve, reject) => {
	// 			const reader = new FileReader();
	// 			reader.onloadend = () => resolve(reader.result);
	// 			reader.onerror = reject;
	// 			reader.readAsDataURL(blob);
	// 		});
	// 	});
}

/**
 * base64转文件对象转
 * @author lizhao
 * @param {object} base64 input选择后的文件对象
 * @param {object} fileName input选择后的文件对象
 * @return {object} file 
 * **/
function base64ToFile(base64 : string, fileName : string) : object {
	// 1.先转为 blob格式  file.content是此文件的base64格式 
	let blob = dataURLtoBlob(base64);
	// 2，在转为 file类型
	let file = blobToFile(blob, fileName);
	return file
}

//1,先将base64转换为blob
function dataURLtoBlob(dataurl) {
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], { type: mime });
}
//2,再将blob转换为file
function blobToFile(theBlob, fileName) {
	theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
	theBlob.name = fileName || '未命名.png';                // 文件名
	return new File([theBlob], fileName, { type: theBlob.type, lastModified: Date.now() });
}



/**
 * 返回格式化后的文件大小
 * @author lizhao
 * @param {number} appByts 文件大小 单位字节
 * @return {string} str 返回格式化文件大小
 * **/
function size(appByts : number) : string {
	const kb = 1024;
	const mb = kb * 1024;
	const gb = mb * 1024;
	const tb = gb * 1024;
	if (appByts > tb) {
		let tbSize = appByts / tb;
		tbSize = Math.floor(tbSize * 100) / 100;
		return `${tbSize}TB`;
	} else if (appByts > gb) {
		let gbSize = appByts / gb;
		gbSize = Math.floor(gbSize * 100) / 100;
		return `${gbSize}GB`;
	} else if (appByts > mb) {
		let mbSize = appByts / mb;
		mbSize = Math.floor(mbSize * 100) / 100;
		return `${mbSize}MB`;
	} else if (appByts > kb) {
		let kbSize = appByts / kb;
		kbSize = Math.floor(kbSize * 100) / 100;
		return `${kbSize}KB`;
	} else {
		return `${appByts}B`;
	}
}
/**
 * 返回文件类型对应的图标
 * @author lizhao
 * @param {string} fileName 传入文件名
 * @return {string} str 返回文件图标
 * **/
function icon(fileName : string) : string {
	if (!fileName) {
		return '文件名不能为空'
	}
	const index = fileName.lastIndexOf('.')
	const suffix = fileName.slice(index + 1, fileName.length)
	if (suffix == 'jpg' || suffix == 'jpeg' || suffix == 'png' || suffix == 'bpm' || suffix == 'BPM' || suffix == 'PNG' ||
		suffix ==
		'gif' || suffix == 'GIF') {
		return ''
	} else if (suffix == 'doc' || suffix == 'docx' || suffix == 'DOC' || suffix == 'DOCX') {
		return ''
	} else if (suffix == 'xlsx' || suffix == 'xls' || suffix == 'XLSX' || suffix == 'XLS') {
		return ''
	} else if (suffix == 'txt' || suffix == 'TXT') {
		return ''
	} else if (suffix == 'zip' || suffix == 'rar') {
		return ''
	} else if (suffix == 'pdf' || suffix == 'PDF') {
		return ''
	} else if (suffix == 'mp4' || suffix == 'wmv' || suffix == 'avi' || suffix == 'MP4' || suffix == 'WMV' || suffix ==
		'AVI') {
		return ''
	} else if (suffix == 'mp3' || suffix == 'm4a' || suffix == 'wma' || suffix == 'MP3' || suffix == 'M4A' || suffix ==
		'WMA') {
		return ''
	} else {
		return ''
	}
}
/**
 * 判断文件类型
 * @author lizhao
 * @param {string} fileName 传入文件名
 * @return {object} obj 返回文件类型
 * **/
function type(fileName : string) : object {
	if (!fileName) {
		return {
			msg: '文件名不能为空'
		}
	}
	const index = fileName.lastIndexOf('.')
	const suffix = fileName.slice(index + 1, fileName.length)
	let result : any = ''
	const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'PNG', 'JPG', 'JPEG', 'BMP', 'GIF']
	const wordList = ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx', 'DOC', 'XLS', 'PPT', 'PDF', 'DOCX', 'XLSX',
		'PPTX', 'txt'
	]
	const videoList = ['mp4', 'wmv', 'avi', 'MP4', 'WMV', 'AVI']
	const audioList = ['mp3', 'm4a', 'wma', 'MP3', 'M4A', 'WMA']
	result = imglist.find(item => item === suffix)
	if (result) {
		return {
			type: 'image',
			suffix
		}
	}
	result = wordList.find(item => item === suffix)
	if (result) {
		return {
			type: 'word',
			suffix
		}
	}
	result = videoList.find(item => item === suffix)
	if (result) {
		return {
			type: 'video',
			suffix
		}
	}
	result = audioList.find(item => item === suffix)
	if (result) {
		return {
			type: 'audio',
			suffix
		}
	}

	return {
		msg: '无法确定文件类型'
	}
}

export default {
	base64,
	size,
	icon,
	type,
	base64ToFile,
	urlToBase64
}
